import 'package:flutter/material.dart' as flutter;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';

import 'services/services.dart';
import 'screens/screens.dart';
import 'constants/constants.dart';

/// 应用程序入口
void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 设置系统UI样式
  SystemChrome.setSystemUIOverlayStyle(
    const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.light,
      systemNavigationBarColor: AppTheme.backgroundDark,
      systemNavigationBarIconBrightness: Brightness.light,
    ),
  );

  // 设置首选方向为竖屏
  await SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);

  runApp(const MusicPlayerApp());
}

/// 音乐播放器应用
class MusicPlayerApp extends StatelessWidget {
  const MusicPlayerApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        // 数据库服务
        Provider<DatabaseService>(
          create: (_) => DatabaseService(),
          dispose: (_, service) => service.close(),
        ),

        // Hive服务
        Provider<HiveService>(
          create: (_) => HiveService(),
          dispose: (_, service) => service.close(),
        ),

        // 音乐库服务
        ChangeNotifierProxyProvider2<DatabaseService, HiveService,
            MusicLibraryService>(
          create: (context) => MusicLibraryService(),
          update: (context, databaseService, hiveService, previous) =>
              previous ?? MusicLibraryService(),
        ),

        // 播放统计服务
        ChangeNotifierProxyProvider2<DatabaseService, MusicLibraryService,
            PlayStatisticsService>(
          create: (context) => PlayStatisticsService(),
          update: (context, databaseService, musicLibraryService, previous) =>
              previous ?? PlayStatisticsService(),
        ),

        // 音频播放服务
        ChangeNotifierProxyProvider3<DatabaseService, MusicLibraryService,
            PlayStatisticsService, AudioPlayerService>(
          create: (context) => AudioPlayerService(),
          update: (context, databaseService, musicLibraryService,
                  statisticsService, previous) =>
              previous ?? AudioPlayerService(),
        ),
      ],
      child: Consumer<AudioPlayerService>(
        builder: (context, audioService, child) {
          return MaterialApp(
            title: AppConstants.appName,
            debugShowCheckedModeBanner: false,
            theme: AppTheme.darkTheme,
            darkTheme: AppTheme.darkTheme,
            themeMode: flutter.ThemeMode.dark,
            home: const AppInitializer(),
            routes: {
              AppRoutes.home: (context) => const HomeScreen(),
              AppRoutes.player: (context) => const PlayerScreen(),
              AppRoutes.library: (context) => const MusicListScreen(),
              AppRoutes.favorites: (context) => const FavoritesScreen(),
              AppRoutes.history: (context) => const HistoryScreen(),
              AppRoutes.settings: (context) => const SettingsScreen(),
            },
          );
        },
      ),
    );
  }
}

/// 应用初始化器
/// 负责初始化各种服务和数据
class AppInitializer extends StatefulWidget {
  const AppInitializer({super.key});

  @override
  State<AppInitializer> createState() => _AppInitializerState();
}

class _AppInitializerState extends State<AppInitializer>
    with TickerProviderStateMixin {
  late AnimationController _logoController;
  late AnimationController _textController;
  late Animation<double> _logoAnimation;
  late Animation<double> _textAnimation;

  bool _isInitialized = false;
  String _initMessage = '正在初始化...';

  @override
  void initState() {
    super.initState();
    _initAnimations();
    _initializeApp();
  }

  /// 初始化动画
  void _initAnimations() {
    _logoController = AnimationController(
      duration: const Duration(milliseconds: 1500),
      vsync: this,
    );

    _textController = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );

    _logoAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _logoController,
      curve: Curves.elasticOut,
    ));

    _textAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _textController,
      curve: Curves.easeInOut,
    ));

    _logoController.forward();
    Future.delayed(const Duration(milliseconds: 500), () {
      _textController.forward();
    });
  }

  /// 初始化应用
  Future<void> _initializeApp() async {
    try {
      // 初始化数据库服务
      setState(() {
        _initMessage = '正在初始化数据库...';
      });

      Provider.of<DatabaseService>(context, listen: false);
      // await databaseService.init(); // 如果有init方法的话

      await Future.delayed(const Duration(milliseconds: 500));

      // 初始化Hive服务
      setState(() {
        _initMessage = '正在初始化本地存储...';
      });

      // 在异步操作前获取服务引用
      late final HiveService hiveService;
      if (!mounted) return;
      hiveService = Provider.of<HiveService>(context, listen: false);
      await hiveService.init();

      await Future.delayed(const Duration(milliseconds: 500));

      // 初始化音乐库服务
      setState(() {
        _initMessage = '正在加载音乐库...';
      });

      final musicLibraryService =
          Provider.of<MusicLibraryService>(context, listen: false);
      await musicLibraryService.init();

      await Future.delayed(const Duration(milliseconds: 500));

      // 初始化播放统计服务
      setState(() {
        _initMessage = '正在初始化播放统计...';
      });

      final statisticsService =
          Provider.of<PlayStatisticsService>(context, listen: false);
      await statisticsService.init();

      await Future.delayed(const Duration(milliseconds: 500));

      // 初始化音频播放服务
      setState(() {
        _initMessage = '正在初始化播放器...';
      });

      final audioService =
          Provider.of<AudioPlayerService>(context, listen: false);
      await audioService.init(); // 初始化音频播放服务

      await Future.delayed(const Duration(milliseconds: 500));

      setState(() {
        _initMessage = '初始化完成！';
        _isInitialized = true;
      });

      // 延迟后跳转到主页
      await Future.delayed(const Duration(milliseconds: 1000));

      if (mounted) {
        Navigator.of(context).pushReplacementNamed(AppRoutes.home);
      }
    } catch (e) {
      setState(() {
        _initMessage = '初始化失败: $e';
      });

      // 显示错误对话框
      _showErrorDialog(e.toString());
    }
  }

  /// 显示错误对话框
  void _showErrorDialog(String error) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        backgroundColor: AppTheme.surfaceDark,
        title: const Text(
          '初始化失败',
          style: TextStyle(
            color: AppTheme.textPrimaryDark,
            fontWeight: FontWeight.bold,
          ),
        ),
        content: Text(
          '应用初始化时发生错误：\n$error',
          style: const TextStyle(
            color: AppTheme.textSecondaryDark,
          ),
        ),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              _initializeApp(); // 重试初始化
            },
            child: const Text(
              '重试',
              style: TextStyle(color: AppTheme.primaryColor),
            ),
          ),
          TextButton(
            onPressed: () {
              SystemNavigator.pop(); // 退出应用
            },
            child: const Text(
              '退出',
              style: TextStyle(color: AppTheme.errorColor),
            ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _logoController.dispose();
    _textController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          gradient: AppTheme.backgroundGradientDark,
        ),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // Logo动画
              ScaleTransition(
                scale: _logoAnimation,
                child: Container(
                  width: 120,
                  height: 120,
                  decoration: BoxDecoration(
                    gradient: AppTheme.primaryGradient,
                    borderRadius: BorderRadius.circular(60),
                    boxShadow: AppTheme.elevatedShadow,
                  ),
                  child: const Icon(
                    Icons.music_note,
                    size: 60,
                    color: Colors.white,
                  ),
                ),
              ),

              const SizedBox(height: AppTheme.spacingXL),

              // 应用名称
              FadeTransition(
                opacity: _textAnimation,
                child: const Text(
                  AppConstants.appName,
                  style: TextStyle(
                    fontSize: 32,
                    fontWeight: FontWeight.bold,
                    color: AppTheme.textPrimaryDark,
                  ),
                ),
              ),

              const SizedBox(height: AppTheme.spacingMedium),

              // 版本信息
              FadeTransition(
                opacity: _textAnimation,
                child: const Text(
                  'v${AppConstants.appVersion}',
                  style: TextStyle(
                    fontSize: AppTheme.fontSizeMedium,
                    color: AppTheme.textSecondaryDark,
                  ),
                ),
              ),

              const SizedBox(height: AppTheme.spacingXL * 2),

              // 加载指示器
              if (!_isInitialized) ...[
                const CircularProgressIndicator(
                  valueColor:
                      AlwaysStoppedAnimation<Color>(AppTheme.primaryColor),
                ),
                const SizedBox(height: AppTheme.spacingLarge),
              ],

              // 初始化消息
              FadeTransition(
                opacity: _textAnimation,
                child: Text(
                  _initMessage,
                  style: TextStyle(
                    fontSize: AppTheme.fontSizeMedium,
                    color: _isInitialized
                        ? AppTheme.successColor
                        : AppTheme.textSecondaryDark,
                  ),
                  textAlign: TextAlign.center,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
